import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';
import { RedisService } from 'src/redis/redis.service';

@Injectable()
export class EmailService {
  constructor(
    private readonly mailerService: MailerService,
    private readonly redisService: RedisService,
  ) {}
  // 生成6位随机验证码 100000 - 999999
  generateVerificationCode(): string {
    return Math.floor(
      Math.random() * (999999 - 100000 + 1) + 100000,
    ).toString();
  }
  // 发送验证码邮件
  async sendVerificationCode(email: string) {
    const code = this.generateVerificationCode();
    try {
      await this.mailerService.sendMail({
        to: email,
        subject: '验证码',
        text: `您的验证码是：${code}，5分钟内有效。`,
        // 或者使用 HTML
        html: `
          <h2>验证码</h2>
          <p>您的验证码是：<strong>${code}</strong></p>
          <p>验证码5分钟内有效。</p>
        `,
      });

      // 可以将验证码保存到 Redis 或数据库中
      await this.redisService.setVerifyCode(email, code);
      return code;
    } catch (error) {
      console.log(error, 'error');
      throw new Error('发送验证码失败');
    }
  }
}
